<template>
<ElSelect :model-value="value" filterable clearable multiple :="$attrs" placeholder="" @update:model-value="onInput">
  <ElOption v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
</ElSelect>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, watch } from 'vue'
import { ElSelect, ElOption } from 'element-plus'
import { getCustomerSubAccountList } from '../api'

interface Props {
  modelValue: any[];
  data: any;
}
const props = withDefaults(defineProps<Props>(), {
  modelValue: () => [],
  data: () => ({})
})

interface Emits {
  'update:model-value': [string]
}
const emit = defineEmits<Readonly<Emits>>()

const options = ref<Array<{ label: string, value: string }>>([])
const value = computed(() => {
  return props.modelValue.map(item => item.subAccountId)
})
const opMap = computed(() => {
  const map = new Map()
  options.value.map(item => {
    map.set(item.value, item)
  })
  return map
})
const onInput = v => {
  const val = v || []
  const list = val.map(id => {
    const obj = opMap.value.get(id) || {}
    return { subAccountId: obj.value, subAccountName: obj.label }
  })
  emit('update:model-value', list)
}

const getOptions = () => {
  getCustomerSubAccountList(props.data)
    .then(res => {
      options.value = res
    })
}

watch(() => props.data.shopId, () => {
  getOptions()
})

onMounted(() => {
  getOptions()
})
</script>
